package infra.persistencia;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

public class Persistencia {

    private static EntityManagerFactory factory = Persistence.createEntityManagerFactory("agendadb");
    private static EntityManager manager = factory.createEntityManager();

    public static EntityTransaction abrir() {
	EntityTransaction tx = manager.getTransaction();
	tx.begin();
	return tx;
    }

    public static <T extends Serializable> T buscar(Class classe, Long id) {
	return (T) manager.find(classe, id);
    }

    public static boolean excluir(Serializable objeto) {
	EntityTransaction tx = abrir();
	try {
	    manager.remove(objeto);
	    tx.commit();
	} catch (Exception e) {
	    tx.rollback();
	    return false;
	}
	return true;
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static List<Serializable> excluirLista(List lista) {
	EntityTransaction tx = abrir();
	try {
	    for (Object objeto : lista) {
		manager.remove(objeto);
	    }
	    tx.commit();
	} catch (Exception e) {
	    tx.rollback();
	}
	return lista;
    }

    public static <T extends Serializable> T persistir(Serializable objeto) {
	EntityTransaction tx = abrir();
	try {
	    manager.persist(objeto);
	    tx.commit();
	} catch (Exception e) {
	    tx.rollback();
	}
	return (T) objeto;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static List<Serializable> persistirLista(List lista) {
	EntityTransaction tx = abrir();
	try {
	    for (Object objeto : lista) {
		manager.persist(objeto);
	    }
	    tx.commit();
	} catch (Exception e) {
	    tx.rollback();
	}
	return lista;
    }

}
